package com.example.service.impl;

import com.example.model.User;
import com.example.repository.UserRepository;
import com.example.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;
import java.util.Random;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private UserRepository userRepository;

    @Override
    public void insertUser() {
        log.info("新增一条数据");
        jdbcTemplate.update("insert into user values(null,?,?);", "小白", 20);
    }

    @Override
    public Optional<User> findById(int id) {
        Optional<User> byId = userRepository.findById(id);

        return byId;
    }

    @Override
    public void insertUserParent() {
        log.info("parent 新增一条数据");
        final var random = new Random(2).nextInt();
        String name ="parent_" + random;
        jdbcTemplate.update("insert into user values(null,?,?);", name,random );

        /**
         * 调用类中方法
         * insertUserParent 方法不加事务注解，子方法添加了注解 会导致事务不生效
         */
        insertUserChild();

    }

    @Override
    @Transactional
    public void insertUserChild() {
        log.info("child 新增一条数据");
        final var random = new Random(2).nextInt();
        String name ="child_" + random;
        jdbcTemplate.update("insert into user values(null,?,?);", name, random);

        // 异常
        throw new RuntimeException("child Exception....................");
    }

    @Override
    @Transactional
    public void threadUser() {
        final var random = new Random(2).nextInt();
        String name = "p_" + Thread.currentThread().getName() + random;
        log.info("主事务1,name={}",name);
        jdbcTemplate.update("insert into user values(null,?,?);", name, random);

        new Thread(()->{
            log.info("事务2,name={}",Thread.currentThread().getName());
            jdbcTemplate.update("insert into user values(null,?,?);", Thread.currentThread().getName(), "12");
            throw new RuntimeException("child Exception....................");
        }).start();

    }
}
